#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

BACKEND_PORT=${BACKEND_PORT:-8000}
FRONTEND_PORT=${FRONTEND_PORT:-5173}

# 杀掉占用端口的进程（先优雅，再强制）
kill_port() {
  local port="$1"
  local pids
  pids=$(lsof -ti tcp:"$port" 2>/dev/null || true)
  if [ -n "${pids:-}" ]; then
    echo "[warn] 端口 $port 被占用，准备结束进程: $pids"
    kill $pids 2>/dev/null || true
    sleep 1
    local still
    still=$(lsof -ti tcp:"$port" 2>/dev/null || true)
    if [ -n "${still:-}" ]; then
      echo "[warn] 进程未退出，强制 kill -9: $still"
      kill -9 $still 2>/dev/null || true
      sleep 0.5
    fi
  fi
}

# 清理历史 PID 文件并尝试结束残留进程
cleanup_pidfiles() {
  for pidfile in /tmp/textlabel-backend.pid /tmp/textlabel-frontend.pid; do
    if [ -f "$pidfile" ]; then
      pid=$(cat "$pidfile" 2>/dev/null || echo "")
      if [ -n "${pid:-}" ] && kill -0 "$pid" 2>/dev/null; then
        echo "[info] 结束历史进程 $pid ($pidfile)"
        kill "$pid" 2>/dev/null || true
        sleep 1
        kill -9 "$pid" 2>/dev/null || true
      fi
      rm -f "$pidfile" || true
    fi
  done
}

echo "[info] 检查端口占用并清理(${BACKEND_PORT}, ${FRONTEND_PORT})"
cleanup_pidfiles
kill_port "$BACKEND_PORT"
kill_port "$FRONTEND_PORT"


echo "[info] 启动后端（uvicorn）"
(
  cd "$ROOT_DIR/server"
  if [ -f requirements.txt ]; then
    # 可通过环境变量覆盖期望主版本： export PYTHON_MAJOR_MINOR=3.12
    PYTHON_MAJOR_MINOR=${PYTHON_MAJOR_MINOR:-3.12}
    # 允许指定绝对路径： export PYTHON_BIN=/opt/python3.12/bin/python3.12
    if [ -n "${PYTHON_BIN:-}" ]; then
      CANDIDATES=("$PYTHON_BIN")
    else
      CANDIDATES=("python${PYTHON_MAJOR_MINOR}" "python${PYTHON_MAJOR_MINOR%.*}" "python3.12" "python3.11" "python3.10" python3)
    fi
    PY_CMD=""
    for c in "${CANDIDATES[@]}"; do
      if command -v "$c" >/dev/null 2>&1; then
        PY_CMD="$c"; break
      fi
    done
    if [ -z "$PY_CMD" ]; then
      echo "[error] 未找到可用 Python 解释器 (候选: ${CANDIDATES[*]})" >&2
      exit 1
    fi
    DESIRED_VER=$($PY_CMD -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")')

    # 检测现有虚拟环境版本是否匹配
    if [ -d .venv ]; then
      if [ -x .venv/bin/python ]; then
        CURRENT_VER=$('./.venv/bin/python' -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null || echo "")
      else
        CURRENT_VER=""
      fi
      if [ "$CURRENT_VER" != "$DESIRED_VER" ]; then
        echo "[info] 现有虚拟环境 Python 版本为 $CURRENT_VER，与期望 $DESIRED_VER 不一致，重建 .venv"
        rm -rf .venv
      fi
    fi

    try_create_venv() {
      local pybin="$1"
      echo "[info] 使用 $pybin 创建虚拟环境 (.venv)"
      if ! "$pybin" -m venv .venv 2>venv.err; then
        if grep -qi 'ensurepip' venv.err; then
          echo "[warn] ensurepip 不可用，可能缺少操作系统包（Debian/Ubuntu 需: apt install python$DESIRED_VER-venv）" >&2
        fi
        return 1
      fi
      return 0
    }

    if [ ! -d .venv ]; then
      if ! try_create_venv "$PY_CMD"; then
        echo "[warn] 首次创建虚拟环境失败，尝试使用 --without-pip + get-pip 兜底"
        rm -rf .venv
        if "$PY_CMD" -m venv --without-pip .venv 2>/dev/null; then
          # shellcheck disable=SC2016
          echo "[info] 下载 get-pip.py 引导安装 pip";
          curl -sS https://bootstrap.pypa.io/get-pip.py -o get-pip.py || { echo '[error] 获取 get-pip.py 失败'; exit 1; }
          ./.venv/bin/python get-pip.py || { echo '[error] get-pip 安装失败'; exit 1; }
          rm -f get-pip.py
        else
          echo "[error] 虚拟环境创建仍失败，退出" >&2
          cat venv.err >&2 || true
          exit 1
        fi
      fi
    fi
    rm -f venv.err 2>/dev/null || true

    # shellcheck disable=SC1091
    source .venv/bin/activate
    # 确保 pip 存在
    if ! command -v pip >/dev/null 2>&1; then
      echo "[warn] 虚拟环境内缺少 pip，尝试引导安装"
      curl -sS https://bootstrap.pypa.io/get-pip.py -o get-pip.py
      python get-pip.py || { echo '[error] 仍无法安装 pip'; exit 1; }
      rm -f get-pip.py
    fi
    pip install --upgrade pip wheel setuptools
    echo "[info] 安装依赖 requirements.txt"
    pip install -r requirements.txt
  fi
  export $(grep -v '^#' "$ROOT_DIR/.env" 2>/dev/null || true | xargs -0 2>/dev/null || true)
  # 兜底环境变量
  export REDIS_URL=${REDIS_URL:-redis://localhost:6379}
  export DATABASE_URL=${DATABASE_URL:-postgresql://ignite_user:ignite_password@localhost:5432/textlabel_db}
  nohup python -m uvicorn app.main:app --host 0.0.0.0 --port ${BACKEND_PORT} --reload >/tmp/textlabel-backend.log 2>&1 &
  echo $! > /tmp/textlabel-backend.pid
)

echo "[info] 启动前端（Vite）"
(
  cd "$ROOT_DIR/web"
  if command -v pnpm &>/dev/null; then
    pnpm install
    pnpm dev --host 0.0.0.0 & echo $! > /tmp/textlabel-frontend.pid  # 关键修改
  elif command -v npm &>/dev/null; then
    npm install
    npm run dev -- --host 0.0.0.0 & echo $! > /tmp/textlabel-frontend.pid  # 关键修改
  else
    echo "[error] 未找到 pnpm/npm，请安装 Node.js 包管理器后再试"
    exit 1
  fi
)

echo "[done] 前端 http://localhost:${FRONTEND_PORT}  后端 http://localhost:${BACKEND_PORT}"
